import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop_z/model/commodity_cart.dart';
import 'package:flutter_shop_z/pages/cart_page/bloc/cart_bloc.dart';
import 'package:flutter_shop_z/shared_preferences/commodity_cart_prefs.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CartCount extends StatelessWidget {
  CommodityCart cart;
  CartCount(this.cart);
  @override
  Widget build(BuildContext context) {
    // return BlocBuilder<CartBloc, CartState>(builder: (context, state) {
    return Container(
      width: ScreenUtil().setWidth(165),
      margin: EdgeInsets.only(top: 5),
      decoration: BoxDecoration(
        border: Border.all(width: 1, color: Colors.black12),
      ),
      child: Row(
        children: <Widget>[
          _reduceBut(context),
          _countArea(),
          _addBut(context),
        ],
      ),
    );
    // });
  }

  //减商品
  Widget _reduceBut(context) {
    return InkWell(
      onTap: () {
        CommodityCartPrefs.deleteCommodityNum(cart.commodityId);
        _updateCartBloc(context);
      },
      child: Container(
        width: ScreenUtil().setWidth(45),
        height: ScreenUtil().setHeight(45),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            right: BorderSide(width: 1, color: Colors.black12),
          ),
        ),
        child: Text('-'),
      ),
    );
  }

  //加商品按钮
  Widget _addBut(context) {
    return InkWell(
      onTap: () {
        CommodityCartPrefs.saveCommodityCart(cart);
        _updateCartBloc(context);
      },
      child: Container(
        width: ScreenUtil().setWidth(45),
        height: ScreenUtil().setHeight(45),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            left: BorderSide(width: 1, color: Colors.black12),
          ),
        ),
        child: Text('+'),
      ),
    );
  }

//数量
  Widget _countArea() {
    var cart2 = cart;
    return Container(
      width: ScreenUtil().setWidth(70),
      height: ScreenUtil().setHeight(45),
      alignment: Alignment.center,
      color: Colors.white,
      child: Text('${cart2.number}'),
    );
  }

  void _updateCartBloc(context) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    BlocProvider.of<CartBloc>(context).add(SetCartEvent(
        sharedPreferences.getString(CommodityCartPrefs.cartListKey)));
  }
}
